<?php
namespace Easy;

class DTO
{
    const FILTER_NULL  = 1;
    const FILTER_EMPTY = 2;

    public function toArr($type = null)
    {
        $arr = get_object_vars($this);
        if (!$type) {
            return $arr;
        }
        foreach ($arr as $k => $v) {
            if ($type == self::FILTER_NULL && is_null($v)) {
                unset($arr[$k]);
            }
            if ($type == self::FILTER_EMPTY && ($v === '' || is_null($v))) {
                unset($arr[$k]);
            }
        }

        return $arr;
    }

    public function toJson()
    {
        $arr = get_object_vars($this);

        return json_encode($arr);
    }

    public function __get($name)
    {
        $cls = get_class($this);
        throw new \Exception("$cls.$name  no define!");
    }


    public function setByArr($arr)
    {
        foreach ($arr as $k => $v) {
            if (property_exists($this, $k)) {
                $this->$k = $v;
            }
        }
    }

    static public function fromArr($arr)
    {
        $callCls = get_called_class();
        $dto     = new $callCls;
        $dto->setByArr($arr);

        return $dto;

    }

    static public function arrIns($arr)
    {
        $callCls = get_called_class();
        $dto     = new $callCls;
        $dto->setByArr($arr);

        return $dto;
    }
}